var types = [];

function endedHandler() {
    var load;
    layui.use('layer', function() {
        var $ = layui.jquery,
            layer = layui.layer;
        load = layer.load()
    });
    var endData = {
        type: 'endData',
        data: {
            courseId: courseId,
            playTime: allTime,
            orderId: orderId,
            allTime: allTime,
            videoId: videoId,
            userId: fd
        }
    };
    ws.send(JSON.stringify(endData));
}

function timeHandler(time) {
    printLog(time);
}

function seekTimeHandler(time) {
    player.videoPlay()
}

function durationHandler(duration) {
    allTime = duration
}

function reconnect(url) {
    setTimeout(function() {
        console.log("重新连接");
        createWebSocket(url)
    }, 2000)
}
var ws;
var wsUrl = (RS.webPath).replace("http://", "ws://") + "/websocketVideoTime";
console.log(wsUrl);

function createWebSocket(url) {
    try {
        if ('WebSocket' in window) {
            ws = new WebSocket(url);
            initEventHandle()
        } else {
            layer.alert("当前浏览器不支持记录播放时间，请使用chrome浏览器进行学习！")
        }
    } catch (e) {}
}

function initEventHandle() {
    ws.onclose = function(event) {
        reconnect(wsUrl)
    };
    ws.onmessage = function(event) {
        console.log(event);
        if ("OK" == event.data) {
            layer.closeAll();
            layer.alert("学习进度已更新!")
        } else if ("ERROR" == event.data) {
            layer.closeAll();
            layer.alert("学习进度更新失败!")
        }
    };
    ws.onerror = function(err) {
        layer.alert("请刷新浏览器重试或（当前浏览器不支持记录播放时间，请使用chrome浏览器进行学习！）")
    };
    ws.onopen = function(evt) {
        console.log("打开连接")
    }
}

function loadedHandler() {
    player.addListener('ended', endedHandler);
    player.addListener('time', timeHandler);
    player.addListener('seekTime', seekTimeHandler);
    player.addListener('duration', durationHandler);
    createWebSocket(wsUrl)
}
if (startT <= 1) {
    startT = 0
}
var videoObject = {
    container: '#video',
    variable: 'player',
    loaded: 'loadedHandler',
    autoplay: true,
    video: [
        [vPath + "/" + cbd2c + "/video.m3u8", 'video/m3u8', '蓝光(暂无)', 0],
        [vPath + "/" + cbd2c + "/video.m3u8", 'video/m3u8', '超清', 0],
        [vPath + "/" + cbd2c + "/720p/video.m3u8", 'video/m3u8', '高清', 10],
        [vPath + "/" + cbd2c + "/480p/video.m3u8", 'video/m3u8', '标清', 0],
    ]
};
if (startT > 0) {
    videoObject['seek'] = startT
}
var player = new ckplayer(videoObject);
var allTime;
$(function() {
    $.fn.raty.defaults.path = webPath + '/static/zcchs/pingfen/lib/img';
    $("#star1").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    $("#star2").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    $("#star3").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    $("#star4").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    $("#star5").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    $("#star6").raty({
        score: 0,
        click: function(score, evt) {
            var id = $(this).attr('id');
            var score = score
        }
    });
    showFen();
    if (userstarcount != 0) {
        $("#pingfenbuttonshow").hide();
        $("#pingfenbuttonhide").show()
    } else {
        $("#pingfenbuttonshow").show();
        $("#pingfenbuttonhide").hide()
    }
});

// DODO fix
// setInterval(function() {
//     $("#chs-mask").css("display", "block");
//     $("#huakuai-content").css("display", "block");
//     $("#huakuai-content").html("<div id='mpanel5'></div>");
//     player.videoPause();
//     $('#mpanel5').pointsVerify({
//         defaultNum: 4,
//         checkNum: 2,
//         vSpace: 5,
//         imgName: ['2.jpg'],
//         imgSize: {
//             width: '600px',
//             height: '200px',
//         },
//         barSize: {
//             width: '600px',
//             height: '40px',
//         },
//         ready: function() {},
//         success: function() {
//             $("#chs-mask").css("display", "none");
//             $("#huakuai-content").css("display", "none");
//             $("#huakuai-content").html("<div id='mpanel5'></div>");
//             player.videoPlay()
//         },
//         error: function() {}
//     })
// }, 60000 * 10);

function printLog(time) {
    var integerNowTime = parseInt(time);
    if (parseInt(integerNowTime) - parseInt(startT) >= 10) {
        startT = integerNowTime;
        var timeData = {
            type: 'updateTime',
            data: {
                courseId: courseId,
                playTime: integerNowTime,
                orderId: orderId,
                allTime: allTime,
                videoId: videoId,
                userId: fd
            }
        };
        ws.send(JSON.stringify(timeData));
    }
}
$("#submitStart").click(function() {
    pingjia(types)
});
var types = [];

function showFen() {
    $.ajax({
        url: webPath + "/index/onlineCourseUser/getPfAvg",
        data: {
            "courseId": courseId,
            "videoId": videoId
        },
        type: "post",
        dataType: "json",
        async: false,
        success: function(re) {
            types = [];
            if (re.length >= 6) {
                for (var i = 0; i < re.length; i++) {
                    var num = re[i].STARAVG;
                    var type = re[i].TYPE;
                    types.push({
                        "type": type
                    });
                    $("#" + type).raty({
                        score: num,
                        number: 5,
                        click: function(score, evt) {
                            var id = $(this).attr('id');
                            var score = score;
                            for (var i = 0; i < types.length; i++) {
                                if (types[i].type == id) {
                                    types[i] = {
                                        "type": id,
                                        "score": score
                                    }
                                }
                            }
                        }
                    })
                }
            } else {
                for (var i = 0; i < 6; i++) {
                    var num = 5;
                    var type = 'star' + (i + 1);
                    types.push({
                        "type": type
                    });
                    $("#" + type).raty({
                        score: num,
                        number: 5,
                        click: function(score, evt) {
                            var id = $(this).attr('id');
                            var score = score;
                            for (var i = 0; i < types.length; i++) {
                                if (types[i].type == id) {
                                    types[i] = {
                                        "type": id,
                                        "score": score
                                    }
                                }
                            }
                        }
                    })
                }
            }
        }
    })
}

function pingjia(data) {
    $.ajax({
        url: webPath + "/index/onlineCourseUser/addVideoStart",
        data: {
            "courseId": courseId,
            "videoId": videoId,
            "data": JSON.stringify(data)
        },
        type: "post",
        dataType: "json",
        async: false,
        success: function(re) {
            if ("suc" == re.status) {
                layui.use('layer', function() {
                    var layer = layui.layer;
                    layer.msg('评价成功!')
                });
                showFen()
            } else if ("err" == re.status) {
                layui.use('layer', function() {
                    var layer = layui.layer;
                    layer.msg('你已评价该课程!')
                });
                showFen()
            } else if ("empty" == re.status) {
                if ("star1" == re.data) {
                    layer.alert("\"课程与描述相符\"没有评价，请评价后再提交")
                } else if ("star2" == re.data) {
                    layer.alert("\"老师的讲解表达\"没有评价，请评价后再提交")
                } else if ("star3" == re.data) {
                    layer.alert("\"教学质量\"没有评价，请评价后再提交")
                } else if ("star4" == re.data) {
                    layer.alert("\"视频清晰度\"没有评价，请评价后再提交")
                } else if ("star5" == re.data) {
                    layer.alert("\"视频音效质量\"没有评价，请评价后再提交")
                } else if ("star6" == re.data) {
                    layer.alert("\"课程实用性\"没有评价，请评价后再提交")
                }
            }
        },
        error: function() {
            layer.msg('系统错误请稍后再试！')
        }
    })
}